<template>
  <div class="container">
    <div class="header">
      <div class="title">闸坝智能调度与安全检测</div>
      <div class="menu">
        <div class="item" @click="router.push({ path: '/szsyGateDamIndex' })">总体概况</div>
        <div class="item active">北江船闸</div>
        <div class="item" @click="router.push({ path: '/szsyLianjiangIndex' })">连江闸坝</div>
      </div>
    </div>
    <div class="main">
      <div class="left-content">
        <div class="top-part">
          <OlArc ref="OlArcRef"></OlArc>
          <div class="filter">
            <el-select
              v-model="shipLock"
              @change="shipLockChange"
              placeholder="请选择船闸"
              style="width: 200px;"                     
            >
              <el-option
                v-for="item in shipLockOptions"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </div>
        </div>
        <div class="bottom-part">
          <div class="base-info">
            <div class="title">基本信息</div>
            <div class="list">
              <div class="info-items" style="border-bottom: 1px solid #F0F0F0;">
                <div class="item width40" style="border-right: 1px solid #F0F0F0;">
                  <div class="name">船闸名称</div>
                  <div class="value">{{ baseInfoObj.name }}</div>
                </div>       
                <div class="item width20" style="border-right: 1px solid #F0F0F0;padding-left: 10px;">
                  <div class="name">所属航道</div>
                  <div class="value">{{ baseInfoObj.channel }}</div>
                </div> 
                <div class="item width40" style="padding-left: 10px;">
                  <div class="name">管理单位</div>
                  <div class="value">{{ baseInfoObj.manage }}</div>
                </div>         
              </div>
              <div class="info-items">
                <div class="item width40" style="border-right: 1px solid #F0F0F0;padding-top: 20px;">
                  <div class="name">船闸等级</div>
                  <div class="value">{{ baseInfoObj.slLevel }}</div>
                </div>       
                <div class="item width20" style="border-right: 1px solid #F0F0F0;padding-top: 20px;padding-left: 10px;">
                  <div class="name">建成年份</div>
                  <div class="value">{{ baseInfoObj.createYear }}</div>
                </div> 
                <div class="item width40" style="padding-top: 20px;padding-left: 10px;">
                  <div class="name">已使用年限</div>
                  <div class="value">{{ baseInfoObj.useYear }}</div>
                </div> 
              </div>
            </div>
          </div>
          <div class="video">
            <div class="title">视频监控</div>
            <div class="subtitle">
              <div class="name">实时视频监控</div>
              <el-select
                v-model="videoPoint"
                size="small"
                :disabled="videoDirectoryData.length?false:true"
                @change="videoPointChange"                
                placeholder="请选择视频点" 
                style="width: 200px;"                    
              >
                <el-option
                  v-for="item in videoDirectoryData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </div>
            <div class="play-video" v-show="videoDirectoryData.length">
              <video 
                id="myVideo" 
                class="video-js vjs-default-skin vjs-big-play-centered"         
                style="object-fit: fill;width: 100%;height: 100%;"
              >
              </video>                  
            </div> 
            <div class="no-video" v-show="videoDirectoryData.length === 0">
              <img src="../../assets/images/pc/error.png" alt="">
              <div class="name">暂无视频</div>      
            </div> 
          </div>
        </div>
      </div>
      <div class="right-content">
        <div class="title">过闸船舶统计分析</div>
        <div class="subtitle">
          <div class="name">北江船闸过闸船舶货物吨位统计分析</div>
          <el-date-picker
            v-model="year"
            type="year"
            size="small"
            :clearable="false"
            @change="yearChange"
            placeholder="请选择年份"
            style="width: 150px;"
          />
        </div>
        <div class="count">
          <div class="count-item">
            <div class="name">总上行船舶数（艘）</div>
            <div class="value">{{ totalUpShipNum }}</div>
          </div>
          <div class="count-item">
            <div class="name">总下行船舶数（艘）</div>
            <div class="value">{{ totalDownShipNum }}</div>
          </div>
        </div>
        <div id="first-chart"></div>
        <div class="subtitle">
          <div class="name">北江船闸过闸船舶货物类型统计分析</div>
          <el-date-picker
            v-model="date"
            type="daterange"
            size="small"
            @change="dateChange"
            :clearable="false"
            value-format="YYYY-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"   
            style="width: 200px;margin-left: 30px;"          
          />
        </div>
        <div class="pie-info">
          <div id="second-chart"></div>
          <div class="pie-table">
            <div class="pie-tbody">
              <div class="pie-tr" v-for="(item,index) in pieChartData" :key="index">
                <div style="display: flex;align-items: center;width: 50%;">
                  <div class="li" :style="`background:${item.itemStyle?item.itemStyle.color:''}`"></div>
                  <div class="pie-td">{{ item.name }}</div>
                </div>     
                <div class="pie-td" style="width: 25%;">{{ item.load }}吨</div>  
                <div class="pie-td" style="width: 25%;">{{ item.value }}%</div>
              </div>
            </div>
          </div>
        </div>
        <div class="subtitle">
          <div class="name">水位情况</div>
          <el-date-picker
            v-model="waterLevelDate"
            type="date"
            placeholder="请选择日期"
            size="small"
            :clearable="false"
            value-format="YYYY-MM-DD"
            @change="waterLevelDateChange"
            style="width: 150px;"
          />
        </div>   
        <div id="third-chart"></div>     
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick, onUnmounted } from 'vue';
  import { useRouter } from "vue-router";
  const router = useRouter();

  //引入echarts
  import * as echarts from 'echarts/core';
  import { TooltipComponent, LegendComponent, GridComponent, DataZoomComponent } from 'echarts/components';
  import { PieChart, BarChart, LineChart } from 'echarts/charts';
  import { CanvasRenderer } from 'echarts/renderers';
  echarts.use([TooltipComponent, LegendComponent, GridComponent, DataZoomComponent, PieChart, BarChart, LineChart, CanvasRenderer]);

  //引入videojs
  import videojs from 'video.js';
  import 'video.js/dist/video-js.css';
  import VideojsZhcnLanguage from 'video.js/dist/lang/zh-CN.json';
  videojs.addLanguage('zh-CN',VideojsZhcnLanguage);

  // 引入api
  import {
    getShipLock, //获取船闸
    baseInfo, //基本信息
    videoDirectory, //获取视频点
    geVideotUrl, //获取视频URL
    goodsTonAlys, //北江船闸过闸船舶货物吨位统计分析
    goodsAnalysis, //北江船闸过闸船舶货物类型统计分析
    waterAlys, //水位情况
  } from "@/bridge-h5/utils/myapi";

  //地图
  import OlArc from "./olArcDetailsBeijiang.vue";
  const OlArcRef = ref(null); 

  //获取船闸
  const shipLock = ref('');
  const shipLockOptions = ref([]);
  const getShipLockFn = () => {
    getShipLock("北江").then((res) => {
      if(res.code === 200 && res.data.length){
        shipLockOptions.value = res.data;
        shipLock.value = res.data[1].name;
        baseInfoFn();
        initVideo();
        goodsTonAlysFn();
        goodsAnalysisFn();
        waterAlysFn();
      }
    });
  };
  const shipLockChange = () => {
    OlArcRef.value.getPositionFn(shipLock.value);
    baseInfoFn();
    videoDirectoryFunction();
    goodsTonAlysFn();
    goodsAnalysisFn();
    waterAlysFn();
  };
  //基本信息
  const baseInfoObj = ref({});
  const baseInfoFn = () => {
    baseInfo(shipLock.value).then((res) => {
      if(res.code === 200 && res.data){
        baseInfoObj.value = res.data;
      }
    });
  };
  //视频监控
  const initVideo = () => {
    nextTick(() => { 
      videojs("myVideo",{
        language: 'zh-CN',  //汉化
        autoplay: true, // true,浏览器准备好时开始播放
        loop: true, // 导致视频一结束就重新开始
        controls: true, //取消视频中的进度条
        muted: true, //是否静音
        preload: 'metadata', //auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）      
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 无法播放媒体源时显示的默认信息
        textTrackDisplay: false,
        techOrder: ['html5', 'flash'],
        controlBar: {
          fullscreenToggle: false, //禁用全屏
        }
      }); 
    });
    videoDirectoryFunction();
  };   
  const videoPoint = ref('');
  const videoDirectoryData = ref([]);
  const videoDirectoryFunction = () => {
    videoDirectory(shipLock.value).then((res) => {
      if(res.code === 200 && res.data.length){
        videoDirectoryData.value = res.data;
        videoPoint.value = res.data[0].id;   
        geVideotUrlFunction();
      }else{
        videoDirectoryData.value = [];
        videoPoint.value = "";   
      }
    });
  };
  const geVideotUrlFunction = () => {
    geVideotUrl(videoPoint.value).then((res) => {
      if(res.code === 200 && res.data){
        const myPlayer = videojs("myVideo"); 
        myPlayer.src([
          {
            type: 'application/x-mpegURL',
            src: res.data.url, //视频播放地址
          }
        ]); 
        myPlayer.play();
      }
    });
  }; 
  const videoPointChange = () => {
    geVideotUrlFunction();
  };

  //北江船闸过闸船舶货物吨位统计分析
  const year = ref(new Date().format("yyyy"));
  const totalUpShipNum = ref(0);
  const totalDownShipNum = ref(0);
  const goodsTonAlysFn = () => {
    goodsTonAlys(
      shipLock.value, 
      `${year.value}-01-01`, 
      `${year.value}-12-31`
    ).then((res) => {
      if(res.code === 200 && res.data){
        totalUpShipNum.value = res.data.totalUpShipNum;
        totalDownShipNum.value = res.data.totalDownShipNum;
        let emptyData = [];
        let num1Data = [];
        let num2Data = [];
        let num3Data = [];
        let num4Data = [];
        let upShipNumData = [];
        let downShipNumData = [];
        res.data.tons.forEach((item) => {
          emptyData.push(item.empty);
          num1Data.push(item.num1);
          num2Data.push(item.num2);
          num3Data.push(item.num3);
          num4Data.push(item.num4);
          upShipNumData.push(item.upShipNum);
          downShipNumData.push(item.downShipNum);
        });

        let stackedChart = echarts.getInstanceByDom(document.getElementById("first-chart"));
        if(stackedChart != null && stackedChart != "" && stackedChart != undefined){
          stackedChart.dispose();
        }
        stackedChart = echarts.init(document.getElementById('first-chart'));
        let option;
        option = {
          tooltip: {
            trigger: 'axis',
            confine: true, //限制在图表区域内 
            formatter: (params) => {
              // console.log(params)
              let template = `<b>${params[0].axisValue}</b><br>` + `上行船舶数<b style="float:right;padding-left: 20px;">${upShipNumData[parseInt(params[0].axisValue.split('月')[0])-1]}艘</b><br>下行船舶数<b style="float:right;padding-left: 20px;">${downShipNumData[parseInt(params[0].axisValue.split('月')[0])-1]}艘</b><br>`; 
              let count = 0;      
              for(let i = 0; i < params.length; i++){              
                let item = params[i];   
                template += item.marker + item.seriesName + `<b style="float:right;padding-left: 20px;">${item.value}艘</b><br>`;    
                count += item.value;                      
              }  
              return template + `<b style="position: absolute;top: 10px; right: 10px;">总共：${count}艘</b>`;
            },  
          },
          legend: {    
            type: 'scroll',         
          },
          grid: {
            top: '60px',
            left: '50px',
            right: '20px',
            bottom: '30px',
          },
          xAxis: [
            {
              type: 'category',
              axisLabel: {
                interval:0, 
              },
              data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '船舶数：艘',
            }
          ],          
          series: [
            {
              name: '空载',
              type: 'bar', 
              stack: 'Search Engine',
              barWidth: "15%",              
              emphasis: {
                //折线图的高亮状态。
                focus: 'series' 
              },
              data: emptyData,              
            },
            {
              name: '0-500吨',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",              
              emphasis: {
                focus: 'series'
              },
              data: num1Data
            },
            {
              name: '500-1000吨',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",              
              emphasis: {
                focus: 'series'
              },
              data: num2Data
            },
            {
              name: '1000-3000吨',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",              
              emphasis: {
                focus: 'series'
              },
              data: num3Data
            },
            {
              name: '3000吨以上',
              type: 'bar',
              stack: 'Search Engine',
              barWidth: "15%",              
              emphasis: {
                focus: 'series'
              },
              data: num4Data
            }
          ]
        };

        option && stackedChart.setOption(option);
      }
    });    
  };
  const yearChange = (val) => {
    year.value = new Date(val).format("yyyy");
    goodsTonAlysFn();
  };
  //北江船闸过闸船舶货物类型统计分析
  const sevenDaysAgo = new Date(new Date().getTime() - 6 * 24 * 60 * 60 * 1000); 
  const sevenDaysAgoFormatted = ref(`${sevenDaysAgo.getFullYear()}-${(sevenDaysAgo.getMonth() + 1).toString().padStart(2, '0')}-${sevenDaysAgo.getDate().toString().padStart(2, '0')}`);
  const date = ref([sevenDaysAgoFormatted.value,new Date().format("yyyy-MM-dd")]);
  const pieChartData = ref([]);
  const goodsAnalysisFn = () => {
    let start = date.value[0];
    let end = date.value[1];
    goodsAnalysis(shipLock.value, start, end).then((res) => {
      if(res.code === 200){  
        let seriesData = [];    
        let colorData = [
          '#6B9BFD','#af71db','#ffa257','#135ddf','#0e8a89','#ffcb32','#4ed9a0','#67cdf7','#67c577','#13cdff',
          '#91cc75','#99cdff','#10757C','#C8778E','#D4B6F4','#8F7059','#EDD18C','#CA3F54','#01448B','#165dff',
          '#FFFF33','#B22222','#FFB6C1','#4B0082','#DDA0DD','#E6E6FA','#F08080','#483D8B','#40E0D0','#330033', 
          '#996666','#996699','#EE0000','#6666FF','#660099','#666699','#0000FF','#FF9933','#CC33CC','#003333',               
        ]; 
        res.data.forEach((item,index) => {
          let obj = {
            name: item.cargoType,
            value: item.rate,
            load: item.load,
            itemStyle: { 
              color: colorData[index]
            }
          };
          seriesData.push(obj);
        });
        pieChartData.value = seriesData;
        let pieChart = echarts.getInstanceByDom(document.getElementById("second-chart"));
        if(pieChart != null && pieChart != "" && pieChart != undefined){
          pieChart.dispose();
        }
        pieChart = echarts.init(document.getElementById('second-chart'));
        let option;
        option = {
          tooltip: {
            trigger: 'item',
            confine: true, //限制在图表区域内
            formatter: function (params) {
              return params.marker + params.data.name + ': ' + params.data.load + '吨，占比：' + params.data.value + '%'
            },    
          },
          // legend: {   
          //   type: 'scroll',          
          // },          
          series: [
            {
              type: 'pie',
              radius: ['70%', '60%'],
              avoidLabelOverlap: false,
              label: {
                show: false,          
              },
              labelLine: {
                show: true, //标签连接线
              },  
              data: seriesData
            }
          ],          
        };
        option && pieChart.setOption(option);
      }
    });     
  };
  const dateChange = () => {
    goodsAnalysisFn();
  };
  //水位情况
  const waterLevelDate = ref(new Date().format('yyyy-MM-dd'));
  const waterAlysFn = () => {
    nextTick(() => {
      waterAlys(shipLock.value, waterLevelDate.value).then((res) => {
        if(res.code === 200){        
          let xAxisData = [];
          let seriesData = [];
          res.data.forEach((item) => {
            xAxisData.push(item.logDate.slice(11,16));          
            seriesData.push(item.waterLevel);
          });
          let lineChart = echarts.getInstanceByDom(document.getElementById("third-chart"));
          if(lineChart != null && lineChart != "" && lineChart != undefined){
            lineChart.dispose();
          }
          lineChart = echarts.init(document.getElementById('third-chart'));
      
          let option;
          option = {
            tooltip: {
              trigger: 'axis',
              confine: true, //限制在图表区域内
              formatter: function (params) {
                let template = `${params[0].axisValue}<br>`;         
                for(let i = 0; i < params.length; i++){
                  let item = params[i];
                  template += item.marker + '水位值: ' + item.value + 'm' + '<br>'
                }  
                return template  
              },
            },
            grid: {
              top: '40px',
              left: '40px',
              right: '12%',
              bottom: '60px',
            },
            dataZoom: [
              {
                show: false,
                type: "inside",                
                zoomLock: false,
              },
            ],
            xAxis: {
              type: 'category',
              name: '时间',
              data: xAxisData,  
              axisLabel: {
                interval:0, 
                rotate: 60,
              },               
            },
            yAxis: {
              type: 'value',
              name: '水位（m）',
            },
            series: [
              {
                data: seriesData,
                type: 'line',
                
              }
            ],
          };
          option && lineChart.setOption(option);           
        }
      });  
    });
  };
  const waterLevelDateChange = () => {
    waterAlysFn();
  };

  onMounted(() => {
    document.title = "闸坝智能调度与安全检测";
    getShipLockFn();
  });
  onUnmounted(() => {
    setTimeout(() => {
      const myPlayer = videojs("myVideo");    
      if(myPlayer){
        myPlayer.dispose();
      }   
    }, 1000);   
  });
</script>

<style lang="scss" scoped>
  @font-face{
    font-family: Din;
    src: url("../../assets/fonts/din.ttf");
  }
  @font-face{
    font-family: Tx;
    src: url("../../assets/fonts/tx.ttf");
  }
  .container{    
    width: 2560px;
    height: 1660px;
    box-sizing: content-box;
    .header{
      height: 40px;    
      display: flex;
      align-items: center;  
      justify-content: space-between; 
      background: #FFFFFF;
      box-shadow: 0px 2px 4px 0px rgba(204,213,232,0.3);
      border-radius: 4px;  
      margin: 16px 16px 0px 16px; 
      padding: 0 16px;
      .title{
        font-family: 'Tx';
        font-weight: 500;
        font-size: 18px;
        color: #262626;
      }
      .menu{
        display: flex;
        align-items: center;
        .item{
          font-weight: 400;
          font-size: 16px;
          color: #262626;
          padding: 6px 18px;
          border-radius: 4px;
        }
        .active{
          color: #FFFFFF;
          background: #0051FF;
        }
      }
    }
    .main{
      box-sizing: content-box;
      height: 1604px;
      margin: 16px;      
      display: flex;
      .left-content{
        width: 1694px;
        height: 1572px;        
        box-sizing: content-box;
        margin-right: 16px;
        .top-part{
          height: 951px;
          margin-bottom: 16px;
          position: relative;
          .filter{
            position: absolute;
            top: 16px;
            left: 16px;
          }
        }
        .bottom-part{
          height: 605px;
          display: flex;
          .base-info{    
            width: 839px;     
            margin-right: 16px;   
            background: #FFFFFF;
            .title{
              height: 48px;
              background: linear-gradient( 90deg, rgba(215,227,255,0.4) 0%, #D7E3FF 100%);
              font-weight: 500;
              font-size: 18px;
              color: #262626;
              line-height: 48px;
              padding-left: 16px;
            }
            .list{        
              margin: 100px 40px;     
              .info-items{
                display: flex;
                .item{
                  .name{
                    font-weight: 400;
                    font-size: 18px;
                    color: #595959;
                    margin-bottom: 4px;
                  }
                  .value{
                    font-weight: 800;
                    font-size: 24px;
                    color: #262626;
                    margin-bottom: 20px;
                  }
                }
                .width40{
                  width: 40%;
                }
                .width20{
                  width: 20%;
                }
              }
            }
          }     
          .video{
            width: 839px;      
            background: #FFFFFF;  
            .title{
              height: 48px;
              background: linear-gradient( 90deg, rgba(215,227,255,0.4) 0%, #D7E3FF 100%);
              font-weight: 500;
              font-size: 18px;
              color: #262626;
              line-height: 48px;
              padding-left: 16px;
            }
            .subtitle{
              height: 48px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 0 16px;
              border-bottom: 1px solid #F0F0F0;
              .name{
                font-weight: 500;
                font-size: 16px;
                color: #262626;
              }
            }
            .play-video{
              height: 485px;
              margin: 8px 16px 16px 16px;
            }
            .no-video{
              height: 485px;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              .name{
                font-weight: 500;
                font-size: 16px;
                color: #262626;
                margin-top: 8px;
              }
            }
          }     
        }
      }
      .right-content{
        width: 818px;
        height: 1572px;       
        box-sizing: content-box;
        background: #FFFFFF;
        .title{
          height: 48px;
          background: linear-gradient( 90deg, rgba(215,227,255,0.4) 0%, #D7E3FF 100%);
          font-weight: 500;
          font-size: 18px;
          color: #262626;
          line-height: 48px;
          padding-left: 16px;
        }
        .subtitle{
          height: 48px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 16px;
          border-bottom: 1px solid #F0F0F0;
          .name{
            font-weight: 500;
            font-size: 16px;
            color: #262626;
          }
        }
        .count{
          height: 30px;
          display: flex;
          align-items: center;
          padding-left: 16px;
          .count-item{
            display: flex;
            align-items: center;
            margin-right: 24px;
            .name{
              font-weight: 400;
              font-size: 16px;
              color: #595959;
            }
            .value{
              font-family: 'Din';
              font-weight: bold;
              font-size: 20px;
              color: #262626;
            }
          }
        }
        #first-chart{
          height: 450px;
        }
        .pie-info{
          display: flex;

          #second-chart{
            height: 430px;
            width: 45%;
          }
          .pie-table {
            height: 430px;
            width: 55%;
            overflow-y: scroll;
            padding: 0 16px;
            .pie-tbody {
              padding-top: 80px;
              font-weight: 400;
              font-size: 16px;
              color: #595959;
              .pie-tr {
                display: flex;
                align-items: center;
                justify-content: space-around;
                margin-bottom: 8px;
                .li{
                  width: 8px;
                  height: 8px;
                  border-radius: 0px 0px 0px 0px;
                  opacity: 1;
                  border-radius: 50%;
                  margin-right: 6px;
                }
              }
            }
          } 
        }  
        #third-chart{
          height: 450px;
        }
      }
    }
  }
</style>